/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LocationsDialog.java
 *
 * Created on Mar 30, 2011, 12:06:41 AM
 */

package client;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumn;
import org.workplicity.inventorycontrol.entry.Location;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

/**
 *
 * @author Harish Giriraju
 */
public class LocationsDialog extends javax.swing.JDialog {

    /** Creates new form LocationsDialog */
    public LocationsDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        this.setTitle("Locations");
        this.setLocationRelativeTo(null);
        initLocationsTable();
    }


    private void initLocationsTable() {
        // Fix the column widths
        locationsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        final int[] WIDTHS = {
             40,  // Id
            100,  // UpdateDate
            205,  // Name
           
        };

        for(int i=0; i < WIDTHS.length; i++) {
            TableColumn col = locationsTable.getColumnModel().getColumn(i);

            col.setPreferredWidth(WIDTHS[i]);
        }

        // Add mouse support for the request table
        // See http://mycodepage.blogspot.com/2006/09/how-to-create-double-click-event-on.html
        locationsTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    JTable target = (JTable) e.getSource();
                    final int row = target.getSelectedRow();

                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                           // call method to perform task on double click
                              editLocationRequest(row);
                        }
                    });
                }
            }
        });

        LocationsTableModel model = (LocationsTableModel) locationsTable.getModel();

        model.refresh();
    }

     private Location editLocationRequest(int row) {
        LocationsTableModel locationModel = (LocationsTableModel) locationsTable.getModel();

        Location selectedLocation = locationModel.getRow(row);

        return selectedLocation;
        
    }

    // Refresh Mehtod
     private void refreshLocations(){

            final LocationsDialog frame = this;
            
            LocationsTableModel model = (LocationsTableModel) locationsTable.getModel();

            final HashMap<Integer, Location> dirty = model.getDirty();

            if (model.getDirty().isEmpty()) {
                model.refresh();
                return;
            }

            String msg = "Some Locations have changed.";
            msg += "\nSave them?";

            int n = JOptionPane.showConfirmDialog(
                    frame,
                    msg,
                    "Confirm",
                    JOptionPane.YES_NO_OPTION);

            if (n == 1) {
                model.refresh();
                return;
            }

            saveLocations();
                
    }// end refresh locations

     //Save method
     private void saveLocations(){

            final LocationsDialog frame = this;
            WorkletContext context = WorkletContext.getInstance();

            LocationsTableModel model = (LocationsTableModel) locationsTable.getModel();
            final HashMap<Integer, Location> dirty = model.getDirty();


            for(Integer id : dirty.keySet()) {
                 Location location = dirty.get(id);


                if (!Helper.insert(location, "Locations", context)) {
                System.out.print("insert failed!");
                }

            }// end for

            model.refresh();

        }// end saveLocation





    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        locationsTable = new javax.swing.JTable();
        refreshButton = new javax.swing.JButton();
        addButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        doneButton = new javax.swing.JButton();
        editLocationButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        locationsTable.setModel(new LocationsTableModel());
        locationsTable.setName("locationsTable"); // NOI18N
        jScrollPane1.setViewportView(locationsTable);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(client.MainFrame.class).getContext().getResourceMap(LocationsDialog.class);
        refreshButton.setIcon(resourceMap.getIcon("refreshButton.icon")); // NOI18N
        refreshButton.setText(resourceMap.getString("refreshButton.text")); // NOI18N
        refreshButton.setName("refreshButton"); // NOI18N
        refreshButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshButtonActionPerformed(evt);
            }
        });

        addButton.setIcon(resourceMap.getIcon("addButton.icon")); // NOI18N
        addButton.setText(resourceMap.getString("addButton.text")); // NOI18N
        addButton.setName("addButton"); // NOI18N
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        deleteButton.setIcon(resourceMap.getIcon("deleteButton.icon")); // NOI18N
        deleteButton.setText(resourceMap.getString("deleteButton.text")); // NOI18N
        deleteButton.setName("deleteButton"); // NOI18N
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        doneButton.setText(resourceMap.getString("doneButton.text")); // NOI18N
        doneButton.setName("doneButton"); // NOI18N
        doneButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                doneButtonActionPerformed(evt);
            }
        });

        editLocationButton.setIcon(resourceMap.getIcon("editLocationButton.icon")); // NOI18N
        editLocationButton.setName("editLocationButton"); // NOI18N
        editLocationButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editLocationButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(refreshButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 61, Short.MAX_VALUE)
                        .addComponent(editLocationButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(addButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(doneButton)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {addButton, deleteButton, editLocationButton, refreshButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(refreshButton)
                    .addComponent(doneButton)
                    .addComponent(deleteButton)
                    .addComponent(addButton)
                    .addComponent(editLocationButton))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {addButton, deleteButton, editLocationButton, refreshButton});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        // TODO add your handling code here:
       SwingUtilities.invokeLater(new Runnable() {

           public void run() {

                refreshLocations();

             }// end run

        });// end swing utilities
    }//GEN-LAST:event_refreshButtonActionPerformed

    // Addbutton code 
    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
        // TODO add your handling code here:
        final LocationsDialog dialog = this;
        refreshLocations();
        SwingUtilities.invokeLater(new Runnable() {
        
            @Override
            public void run() {
                try {
                    
                    Location location = new Location();
                    AddLocationDialog locationDialog =
                    new AddLocationDialog( null ,location, true);
                    locationDialog.setVisible(true);
                    locationDialog.setTitle("Add New Locations");

                    refreshLocations();

                } catch (Exception e) {
                    //Logger.log(e.toString());
                }
            }
        });
    }//GEN-LAST:event_addButtonActionPerformed

    // Delete button code
    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        // TODO add your handling code here:
        final LocationsDialog frame = this;

        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                LocationsTableModel model = (LocationsTableModel) locationsTable.getModel();
                int row = locationsTable.getSelectedRow();
                if (row == -1){
                        JOptionPane.showMessageDialog(frame,
                        "Please select a location from the table to delete ",
                        "No selection made",
                        JOptionPane.ERROR_MESSAGE);
                }
                else
                 {
                        Location location = editLocationRequest(row);
                       // TODO add delete Location handling code here:
                        String msg = "Are sure to delete this Location?";

                        int n = JOptionPane.showConfirmDialog(
                                null,
                                msg,
                                "Confirm",
                                JOptionPane.YES_NO_OPTION);

                        if (n == 1) {
                            return;
                        }

                try{
                        WorkletContext context = WorkletContext.getInstance();
                        if (!Helper.delete(location, "Locations", context)) {
                            System.out.print("Delete failed!");
                        }
                        else
                        {
                            System.out.print("Delete successful");
                        }

                }catch(Exception ex){

               }
              }
                 refreshLocations();
                 model.fireTableDataChanged();

                }

          });

    }//GEN-LAST:event_deleteButtonActionPerformed

    private void doneButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_doneButtonActionPerformed
        // TODO add your handling code here:
       SwingUtilities.invokeLater(new Runnable() {

           public void run() {

                refreshLocations();

             }// end run

        });// end swing utilities
        dispose();
    }//GEN-LAST:event_doneButtonActionPerformed

    private void editLocationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editLocationButtonActionPerformed
        // TODO add your handling code here:
        final LocationsDialog frame = this;
        
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {

                int row = locationsTable.getSelectedRow();
                if (row == -1){

                        JOptionPane.showMessageDialog(frame,
                        "Please select a Location from the table to view ",
                        "No selection made",
                        JOptionPane.ERROR_MESSAGE);

                }
                else
                 {
                        // Displays add Location dialog
                        Location location = new Location();
                        location = editLocationRequest(row);
                        AddLocationDialog locationDialog =
                                new AddLocationDialog( null ,location, true);
                        locationDialog.setVisible(true);
                        locationDialog.setTitle("Edit location");

                        refreshLocations();
                }
            }
        });

    }//GEN-LAST:event_editLocationButtonActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {

                }
                
                LocationsDialog dialog = new LocationsDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent e) {
                    System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton doneButton;
    private javax.swing.JButton editLocationButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable locationsTable;
    private javax.swing.JButton refreshButton;
    // End of variables declaration//GEN-END:variables

}
